package com.example.figurehecheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.figurehecheng.common.config.checkObjAllFieldsIsNull;
import com.example.figurehecheng.common.constant.MessageConstant;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.common.exception.AccountExist;
import com.example.figurehecheng.common.result.PageResult;
import com.example.figurehecheng.common.utils.AliOssUtil;
import com.example.figurehecheng.domain.dto.FoodDTO;
import com.example.figurehecheng.domain.entity.Food;
import com.example.figurehecheng.domain.entity.Image;
import com.example.figurehecheng.domain.entity.Merchant;
import com.example.figurehecheng.domain.vo.FoodVO;
import com.example.figurehecheng.mapper.FoodMapper;
import com.example.figurehecheng.service.IFoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.figurehecheng.service.IImageService;
import com.example.figurehecheng.service.IMerchantService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 宇科工作室
 * @since 2024-10-18
 */
@Service
@RequiredArgsConstructor
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements IFoodService {


    private final IImageService imageService;

    private final AliOssUtil aliOssUtil;

    private final IMerchantService iMerchantService;
    /**
     * 获取菜品相关信息
     *
     * @return
     */
    @Override
    @Transactional
    public PageResult getDishAll(String name, Integer pageNum, Integer pageSize) {

        //分页查询获取对应的菜品
        Page<Food> pages = Page.of(pageNum, pageSize);
        Page<Food> food = lambdaQuery().
                eq(Food::getCanteenId, BaseContext.getCurrentId())
                .like(ObjectUtil.isNotEmpty(name),Food::getName, name)
                .page(pages);

        List<FoodVO> foodVOS = new ArrayList<>();
        //根据商家id获取对应图片
        List<Image> images = imageService.list(new QueryWrapper<Image>()
                .lambda().eq(Image::getShopId, BaseContext.getCurrentId()));

        for (int i=0;i< food.getRecords().size();i++){
            for (int j=0;j<images.size();j++){
                if (ObjectUtil.equal(food.getRecords().get(i).getId(),images.get(j).getProgramId())){
                    FoodVO foodVO = BeanUtil.copyProperties(food.getRecords().get(i), FoodVO.class);
                    foodVO.setPhotograph(images.get(j).getPhotograph());
                    foodVOS.add(foodVO);
                }
            }
        }

        return   PageResult.builder()
                .total(food.getTotal())
                .records(foodVOS)
                .pages(food.getPages())
                .build();
    }

    /**
     * 修改菜品相关信息
     * @param foodDto
     */
    @Override
    @Transactional
    public void updateDish(FoodDTO foodDto) {
         //查看对象所有信息是否为空
        if (checkObjAllFieldsIsNull.objCheckIsNull(foodDto)) {
            throw new AccountExist(MessageConstant.COUPON_NOT_NULL);
        }

        lambdaUpdate().set(Food::getName, foodDto.getName())
                .set(Food::getIntroduce, foodDto.getIntroduce())
                .set(Food::getPrice, foodDto.getPrice())
                .set(Food::getFoodTypeid, foodDto.getFoodTypeid())
                .eq(Food::getId, foodDto.getId())
                .eq(Food::getCanteenId, BaseContext.getCurrentId())
                .update();

        imageService.update(new UpdateWrapper<Image>()
                        .lambda()
                .set(Image::getPhotograph, foodDto.getPhotograph())
                .eq(Image::getProgramId, foodDto.getId())
                .eq(Image::getShopId, BaseContext.getCurrentId()));
    }

    /**
     * 删除菜品相关信息
     * @param
     */
    @Override
    @Transactional
    public void deleteDish(FoodDTO foodDTO) {

        remove(new QueryWrapper<Food>()
                .lambda().eq(Food::getId, foodDTO.getId())
                .eq(Food::getCanteenId, BaseContext.getCurrentId()));

        boolean remove = imageService.remove(new QueryWrapper<Image>()
                        .lambda().eq(Image::getProgramId, foodDTO.getId())
                .eq(Image::getShopId, BaseContext.getCurrentId()));
        if (remove){
             aliOssUtil.delete(foodDTO.getPhotograph());
        }
    }

    @Override
    @Transactional
    public void addDish(FoodDTO foodDTO) {

        if (!ObjectUtil.isAllNotEmpty(foodDTO.getPhotograph(),foodDTO.getFoodTypeid(),foodDTO.getName(),foodDTO.getIntroduce(),foodDTO.getPrice())) {
            throw new AccountExist(MessageConstant.COUPON_NOT_NULL);
        }
        //先添加菜品
        Food food = BeanUtil.copyProperties(foodDTO, Food.class);
        food.setCanteenId(BaseContext.getCurrentId().intValue());
        save(food);
        //获取菜品id
        Food foods = lambdaQuery().eq(Food::getCanteenId, BaseContext.getCurrentId())
                .eq(Food::getName, foodDTO.getName())
                .one();
        //获取对应的分类
        Merchant merchant = iMerchantService.getOne(new QueryWrapper<Merchant>()
                .lambda().eq(Merchant::getId, BaseContext.getCurrentId()));
        //将获取的菜品id添加到图片表中
        imageService.save(Image.builder()
                .shopId(BaseContext.getCurrentId().intValue())
                .programId(foods.getId())
                .photograph(foodDTO.getPhotograph())
                .type(merchant.getRole())
                .build());
    }

}
